package com.originskyseed.platform.user.controller;

import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.common.api.util.PasswordUtil;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.user.i18n.RegisterResponseMsg;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Channel;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IChannelService;
import com.originskyseed.platform.user.vo.request.ChannelRequestVO;

/**
 * 渠道信息表Controller类（OSI_CHANNEL）
 *
 * @author WuZhuoXi
 */
@Controller
@RequestMapping("/channel")
@BaseLocaleResource(localeFileName = "i18n_user")
public class ChannelController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ChannelController.class);

	@DubboReference
	private IChannelService channelService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/channelList.json", method = RequestMethod.POST)
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Channel>> channelList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Channel>> result = null;
		try {
			// 请求对象
			ChannelRequestVO requestVO = this.getParameterBean(ChannelRequestVO.class);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if(userInfo!=null) {
				requestVO.setCreatorId(userInfo.getId());
			}

			// 分页查询
			BasePage<Channel> page = new BasePage<Channel>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.channelService.selectListByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<Channel>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Channel>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/channelSave.json", method = RequestMethod.POST)
	@RequiredParams(names = {})
	public BaseResponseBody<Channel> channelSave(HttpServletRequest request) {
		BaseResponseBody<Channel> result = null;
		try {
			// 请求对象
			Channel channel = this.getParameterBean(Channel.class);

			if (StringUtils.isNotBlank(channel.getId())) {
				this.channelService.updateByPrimaryKeySelective(channel);
			} else {
				// 判断密码
				if (channel.getPassword().length() < 6) {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), "密码长度不能小于六位数", false);
				} else if (channel.getPassword().length() > 15) {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), "密码长度不能大于十五位数", false);
				} else if (!channel.getPassword().matches("^(?=.*[0-9])(?=.*[a-zA-Z])[0-9A-Za-z!@#$%^&*,\\.]{6,15}$")) {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), RegisterResponseMsg.PASSWORD_SIMPLE_ERROR.getMsg()), false);
				}
				UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
				channel.setCreator(userInfo.getName());
				channel.setCreatorId(userInfo.getId());
				channel.setPassword(DigestUtils.md5DigestAsHex(channel.getPassword().getBytes()));
				channel.setChannelId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
				this.channelService.insertSelective(channel);
			}
			result = new BaseResponseBody<Channel>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), channel);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Channel>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/channelDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> channelDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.channelService.deleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 重置密码
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/resetPassword.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody<String> resetPassword(HttpServletRequest request) {
		BaseResponseBody<String> result = null;
		try {
			// 请求对象
			Channel channel = this.getParameterBean(Channel.class);
			String password = PasswordUtil.getStringRandom(6);
			channel.setPassword(password);
			this.channelService.updateByPrimaryKeySelective(channel);
			result = new BaseResponseBody<String>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), password);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<String>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}
}